package com.qingcloud.adminbackend.service.impl;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.google.common.collect.ImmutableMap;
import com.qingcloud.adminbackend.constant.WamingConstant;
import com.qingcloud.adminbackend.entity.config.SysSensorFactorConfig;
import com.qingcloud.adminbackend.entity.equipment.EquipmentMgrBO;
import com.qingcloud.adminbackend.entity.equipment.ModelDTO;
import com.qingcloud.adminbackend.entity.user.SysUser;
import com.qingcloud.adminbackend.mapper.*;
import com.qingcloud.adminbackend.mapper.*;
import com.qingcloud.adminbackend.utils.CommonUtil;
import com.qingcloud.base.constant.SecurityConstants;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.*;
import java.util.stream.Collectors;

@Service
public class BaseServiceImpl {

    private static final Logger logger = LoggerFactory.getLogger(BaseServiceImpl.class);

    @Resource
    private SysSensorFactorConfigMapper sysSensorFactorConfigMapper;
    @Resource
    private SysEquipmentMapper sysEquipmentMapper;
    @Resource
    private SysUserMapper sysUserMapper;
    @Resource
    private SysStationMapper sysStationMapper;
    @Resource
    private SysUserRoleMapper sysUserRoleMapper;

    /**
     * 组装监测因子
     * 将组合因子拆分成具体监测因子
     *
     * @param factors
     * @return
     */
    public List<String> assembleSensorFactor(List<String> factors, List<SysSensorFactorConfig> sensorFactorConfigs) {
        sensorFactorConfigs.forEach(it -> {
            if (factors.contains(it.getFactorId()) && it.getFactorContent().contains(",")) {
                List<String> descIds = Arrays.asList(it.getFactorContent().split(","));
                descIds.forEach(descId -> {
                    factors.add(descId);
                });
            }
        });
        return factors;
    }

    /**
     * 获取监测因子的内容map和描述map
     *
     * @param map
     * @param mapDesc
     * @return
     */
    public void sensorFactorMap(Map<Integer, String> map, Map<Integer, String> mapDesc, List<SysSensorFactorConfig> sensorFactorConfigs) {
        if (sensorFactorConfigs != null) {
            //查询所有的检测因子
            List<SysSensorFactorConfig> configs = sysSensorFactorConfigMapper.selectByMap(ImmutableMap.of());
            configs.forEach(it -> {
                sensorFactorConfigs.add(it);
            });
        }
        if (map != null) {
            //监测因子内容map
            Map<Integer, String> factorMap = sensorFactorConfigs.stream().collect(Collectors.toMap(SysSensorFactorConfig::getFactorId, SysSensorFactorConfig::getFactorContent));
            factorMap.forEach((k, v) -> map.put(k, v));
        }
        if (mapDesc != null) {
            //监测因子内容描述map
            Map<Integer, String> factormapDesc = sensorFactorConfigs.stream().collect(Collectors.toMap(SysSensorFactorConfig::getFactorId, SysSensorFactorConfig::getFactorDesc));
            factormapDesc.forEach((k, v) -> mapDesc.put(k, v));
        }
    }

    /**
     * 获取监测因子的内容map和描述map
     *
     * @return
     */
    public Map<Integer, String> sensorFactorDescMap() {
        //查询所有的检测因子
        List<SysSensorFactorConfig> configs = sysSensorFactorConfigMapper.selectByMap(ImmutableMap.of());
        //监测因子内容描述map
        return configs.stream().collect(Collectors.toMap(SysSensorFactorConfig::getFactorId, SysSensorFactorConfig::getFactorDesc));
    }

    /**
     * 获取监测因子的内容map和描述map
     *
     * @return
     */
    public Map<Integer, String> sensorFactorContentMap() {
        //查询所有的检测因子
        List<SysSensorFactorConfig> configs = sysSensorFactorConfigMapper.selectByMap(ImmutableMap.of());
        //监测因子内容描述map
        return configs.stream().collect(Collectors.toMap(SysSensorFactorConfig::getFactorId, SysSensorFactorConfig::getFactorContent));
    }

    /**
     * 获取监测因子的内容和描述tooltip
     *
     * @param sensorFactors （例如：1,2,3,4）
     * @param map
     * @param mapDesc
     * @return
     */
    public Map<String, String> splitSensorFactor(Map<Integer, String> map, Map<Integer, String> mapDesc, String sensorFactors) {
        //当前产品型号的监测因子
        if (StrUtil.isBlank(sensorFactors)) {
            return null;
        }
        //监测因子
        String factor = "";
        //监测因子详细描述tooltip
        String tooltip = "";
        List<String> ids = Arrays.asList(sensorFactors.split(","));
        for (String id : ids) {
            if (factor.indexOf(mapDesc.get(Integer.parseInt(id))) == -1) {
                factor = factor.concat(mapDesc.get(Integer.parseInt(id))).concat(" ");
            }
            String desc = map.get(Integer.parseInt(id));
            if (desc.contains(",")) {
                //拆分不是具体的监测因子组装监测因子tooltip
                List<String> descIds = Arrays.asList(desc.split(","));
                for (String descId : descIds) {
                    if (tooltip.indexOf(mapDesc.get(Integer.parseInt(descId))) == -1) {
                        tooltip = tooltip.concat(mapDesc.get(Integer.parseInt(descId))).concat(" ");
                    } else {
                        factor = factor.replaceAll(mapDesc.get(Integer.parseInt(descId)).concat(" "), "");
                    }
                }
            } else {
                if (tooltip.indexOf(desc) == -1) {
                    tooltip = tooltip.concat(desc).concat(" ");
                }
            }
        }
        Map<String, String> hashMap = new HashMap<>();
        hashMap.put("factor", factor);
        hashMap.put("tooltip", tooltip);
        return hashMap;
    }

    /**
     * 组合监测因子
     *
     * @return
     */
    public List<SysSensorFactorConfig> findSensorFactorConfig() {
        QueryWrapper<SysSensorFactorConfig> roleFunQuery = new QueryWrapper<>();
        roleFunQuery.in("factor_type", 2);
        List<SysSensorFactorConfig> configs = sysSensorFactorConfigMapper.selectList(roleFunQuery);
        return configs;
    }

    /**
     * 具体监测因子转换组合因子
     *
     * @param configs
     * @param sensorFactors
     * @return
     */
    public String spellSensorFactorConfig(List<SysSensorFactorConfig> configs, String sensorFactors) {
        String tooltip = "";
        List<String> list = new ArrayList<>();
        if (StrUtil.isNotBlank(sensorFactors)) {
            List<String> factorIds = Arrays.asList(sensorFactors.split(","));
            List<String> arrList = new ArrayList<>(factorIds);
            for (SysSensorFactorConfig it : configs) {
                List<String> descIds = Arrays.asList(it.getFactorContent().split(","));
                if (factorIds.containsAll(descIds)) {
                    descIds.forEach(descId -> {
                        list.add(descId);
                    });
                    arrList.add(String.valueOf(it.getFactorId()));
                }
            }
            arrList = CommonUtil.removeAll(arrList, list);
            tooltip = sysSensorFactorConfigMapper.orderSensorFactors(arrList);
        }
        return tooltip;
    }


    /**
     * 获取监测因子的内容
     *
     * @param sensorFactors （例如：1,2,3,4）
     * @param mapDesc
     * @return
     */
    public String getFactor(Map<Integer, String> mapDesc, String sensorFactors) {
        //当前产品型号的监测因子
        if (StrUtil.isBlank(sensorFactors)) {
            return null;
        }
        //监测因子
        String factor = "";
        List<String> ids = Arrays.asList(sensorFactors.split(","));
        for (String id : ids) {
            if (factor.indexOf(mapDesc.get(Integer.parseInt(id))) == -1) {
                factor = factor.concat(mapDesc.get(Integer.parseInt(id))).concat(" ");
            }
        }
        return factor;
    }

    /**
     * 获取监测因子的内容
     *
     * @param sensorFactors （例如：1,2,3,4）
     * @param mapDesc
     * @return
     */
    public List<String> getFactorDetails(Map<Integer, String> mapDesc, List<String> sensorFactors) {
        //当前产品型号的监测因子
        if (sensorFactors == null || sensorFactors.size() == 0) {
            return new ArrayList<>();
        }
        //监测因子
        List<String> list = new ArrayList<>();
        for (String id : sensorFactors) {
            if (!list.contains(mapDesc.get(Integer.parseInt(id)))) {
                list.add(mapDesc.get(Integer.parseInt(id)));
            }
        }
        return list;
    }

    /**
     * 获取监测因子的描述tooltip
     *
     * @param sensorFactors （例如：1,2,3,4）
     * @param map
     * @param mapDesc
     * @return
     */
    public String getTooltip(Map<Integer, String> map, Map<Integer, String> mapDesc, String sensorFactors) {
        //当前产品型号的监测因子
        if (StrUtil.isBlank(sensorFactors)) {
            return null;
        }
        //监测因子详细描述tooltip
        String tooltip = "";
        List<String> ids = Arrays.asList(sensorFactors.split(","));
        for (String id : ids) {
            String desc = map.get(Integer.parseInt(id));
            if (desc.contains(",")) {
                //拆分不是具体的监测因子组装监测因子tooltip
                List<String> descIds = Arrays.asList(desc.split(","));
                for (String descId : descIds) {
                    tooltip = tooltip.concat(mapDesc.get(Integer.parseInt(descId))).concat(" ");
                }
            } else {
                tooltip = tooltip.concat(desc).concat(" ");
            }
        }
        return tooltip;
    }

    /**
     * 功能描述: 监测因子Ids转换成字符串
     *
     * @param:
     * @return:
     * @auther: Destiny
     * @date: 2019/4/23 14:36
     */
    public String getSensorFactor(String sensorFactors) {
        //当前产品型号的监测因子
        if (StrUtil.isBlank(sensorFactors)) {
            return "";
        }
        //监测因子
        String factor = "";
        List<String> ids = Arrays.asList(sensorFactors.split(","));

        return sysSensorFactorConfigMapper.getSensorFactorStr(ids);
    }

    /**
     * 功能描述: 监测因子拆分
     *
     * @param:
     * @return:
     * @auther: Destiny
     * @date: 2019/4/23 14:44
     */
    public String getSensorFactorSplit(String sensorFactors) {
        //当前产品型号的监测因子
        if (StrUtil.isBlank(sensorFactors)) {
            return "";
        }
        //监测因子
        String factor = "";
        List<String> ids = Arrays.asList(sensorFactors.split(","));

        return sysSensorFactorConfigMapper.getSensorFactorSplitStr(ids);
    }

    /**
     * 有权限访问的设备编号
     *
     * @param userId      用戶id
     * @param orderIds    订单id集合
     * @param orgIds      客户id集合
     * @param stationFlag 是否查看设备池(0,1)
     * @return
     */
    public List<ModelDTO> getEquipmentIds(String userId, List<String> orderIds, List<String> orgIds, int stationFlag) {
        if (orderIds == null) {
            orderIds = new ArrayList<>();
        }
        if (orgIds == null) {
            orgIds = new ArrayList<>();
        }
        SysUser sysUser = sysUserMapper.selectById(userId);
        //登录用户为空
        if (sysUser == null) {
            return Collections.emptyList();
        }
        //是否超管
        if (SecurityConstants.ADMIN_USER_NAME.equals(sysUser.getUserName())) {
            //查询设备池设备
            if ((orderIds.size() == 0 && orgIds.size() == 0) && stationFlag == 1) {
                return sysEquipmentMapper.getEquipmentPoolIds();
            }
            //筛选符合的设备
            if ((orderIds.size() > 0 || orgIds.size() > 0) && stationFlag == 0) {
                return sysEquipmentMapper.getEquipmentAllIds(orderIds, orgIds);
            }
            //筛选符合的设备
            if ((orderIds.size() > 0 || orgIds.size() > 0) && stationFlag == 1) {
                return sysEquipmentMapper.getEquipmentAllModelIds(orderIds, orgIds);
            }
            //筛选全部设备
            return sysEquipmentMapper.getEquipmentAllIds(orderIds, orgIds);
        }
        boolean isAdmin = false;
        //完全管理权限
        if (sysUser.getAdminFlag() == 1) {
            isAdmin = true;
        }
        //是否有管理设备池权限
        boolean isPool = false;
        if (sysUser.getStationFlag() == 1) {
            isPool = true;
        }
        if (isPool) {
            //查询设备池设备
            if ((orderIds.size() == 0 && orgIds.size() == 0) && stationFlag == 1) {
                return sysEquipmentMapper.getEquipmentPoolIds();
            }
            //筛选可管理的设备
            if ((orderIds.size() > 0 || orgIds.size() > 0) && stationFlag == 0) {
                return sysEquipmentMapper.getEquipmentMgrIds(isAdmin, userId, orderIds, orgIds);
            }
            //筛选设备池和可管理的设备
            return sysEquipmentMapper.getEquipmentIds(isAdmin, userId, orderIds, orgIds);
        } else {
            //筛选可管理的设备
            return sysEquipmentMapper.getEquipmentMgrIds(isAdmin, userId, orderIds, orgIds);
        }
    }

    /**
     * 有权限访问的设备编号
     *
     * @param userId         用戶id
     * @param equipmentMgrBO 请求对象
     * @return
     */
    public IPage<ModelDTO> getEquipmentIdsPage(String userId, EquipmentMgrBO equipmentMgrBO) {
        List<String> orderIds = equipmentMgrBO.getOrderIds();
        List<String> orgIds = equipmentMgrBO.getOrgIds();
        String equipmentId = null;
        String productType = null;
        if (equipmentMgrBO.getEquipmentId() != null && !equipmentMgrBO.getEquipmentId().equalsIgnoreCase("")) {
            equipmentId = "%" + equipmentMgrBO.getEquipmentId() + "%";
        }
        if (equipmentMgrBO.getEquipmentId() != null && !equipmentMgrBO.getEquipmentId().equalsIgnoreCase("")) {
            productType = "%" + equipmentMgrBO.getProductType() + "%";
        }
        Page<ModelDTO> page = new Page<>(equipmentMgrBO.getPage(), equipmentMgrBO.getPerPage());
        int stationFlag = equipmentMgrBO.getStationFlag();
        if (orderIds == null) {
            orderIds = new ArrayList<>();
        }
        if (orgIds == null) {
            orgIds = new ArrayList<>();
        }
        SysUser sysUser = sysUserMapper.selectById(userId);
        //登录用户为空
        if (sysUser == null) {
            logger.error("USER IS NULL");
            return null;
        }
        //是否超管
        if (SecurityConstants.ADMIN_USER_NAME.equals(sysUser.getUserName())) {
            //查询设备池设备
            if ((orderIds.size() == 0 && orgIds.size() == 0) && stationFlag == 1) {
                return sysEquipmentMapper.getEquipmentPoolIdsPage(page, equipmentId, productType);
            }
            //筛选符合的设备
            if ((orderIds.size() > 0 || orgIds.size() > 0) && stationFlag == 0) {
                return sysEquipmentMapper.getEquipmentAllIdsPage(page, orderIds, orgIds, equipmentId, productType);
            }
            //筛选符合的设备
            if ((orderIds.size() > 0 || orgIds.size() > 0) && stationFlag == 1) {
                return sysEquipmentMapper.getEquipmentAllModelIdsPage(page, orderIds, orgIds, equipmentId, productType);
            }
            //筛选全部设备
            return sysEquipmentMapper.getEquipmentAllIdsPage(page, orderIds, orgIds, equipmentId, productType);
        }
        boolean isAdmin = false;
        //完全管理权限
        if (sysUser.getAdminFlag() == 1) {
            isAdmin = true;
        }
        //是否有管理设备池权限
        boolean isPool = false;
        if (sysUser.getStationFlag() == 1) {
            isPool = true;
        }
        if (isPool) {
            //查询设备池设备
            if ((orderIds.size() == 0 && orgIds.size() == 0) && stationFlag == 1) {
                return sysEquipmentMapper.getEquipmentPoolIdsPage(page, equipmentId, productType);
            }
            //筛选可管理的设备
            if ((orderIds.size() > 0 || orgIds.size() > 0) && stationFlag == 0) {
                return sysEquipmentMapper.getEquipmentMgrIdsPage(page, isAdmin, userId, orderIds, orgIds, equipmentId, productType);
            }
            //筛选设备池和可管理的设备
            return sysEquipmentMapper.getEquipmentIdsPage(page, isAdmin, userId, orderIds, orgIds, equipmentId, productType);
        } else {
            //筛选可管理的设备
            return sysEquipmentMapper.getEquipmentMgrIdsPage(page, isAdmin, userId, orderIds, orgIds, equipmentId, productType);
        }
    }

    /**
     * 有权限访问的监测点编号
     *
     * @param userId   用戶id
     * @param orderIds 订单id集合
     * @param orgIds   客户id集合
     * @param status   状态 null 所有 1有效
     * @param isAll    是否所有状态的监测点
     * @return
     */
    public List<ModelDTO> getStationIds(String userId, List<String> orderIds, List<String> orgIds,
                                        String workType, Integer status, boolean isAll) {
        if (orderIds == null) {
            orderIds = new ArrayList<>();
        }
        if (orgIds == null) {
            orgIds = new ArrayList<>();
        }
        //是否超管
        if (WamingConstant.ADMIN_USER_ID.equals(userId)) {
            //筛选全部监测点
            return sysStationMapper.getStationAllIds(orderIds, orgIds, workType, status);
        }
        SysUser sysUser = sysUserMapper.selectById(userId);
        //登录用户为空
        if (sysUser == null) {
            return Collections.emptyList();
        }
        boolean isAdmin = false;
        //完全管理权限
        if (sysUser.getAdminFlag() == 1) {
            isAdmin = true;
        }
        //筛选可管理的监测点
        if (isAll) {
            return sysStationMapper.getAllStationMgrIds(isAdmin, userId, orderIds, orgIds, workType);
        }
        return sysStationMapper.getStationMgrIds(isAdmin, userId, orderIds, orgIds, workType);
    }

    public Set<ModelDTO> getUserStationIds(String userId, String workType) {

        //企业管理员ID
        List<ModelDTO> companyManageStation = sysStationMapper.findCompanyManagerStation(userId, workType);

        //企业设备管理员ID
        List<ModelDTO> allStationList = sysStationMapper.findCompanyEquipmentManagerStation(userId, workType);

        allStationList.addAll(companyManageStation);
        return new HashSet<>(allStationList);
    }

    /**
     * 查询用户可读设备编号
     *
     * @param stationIdSet 监测点编号
     * @return
     */
    public Set<String> findEquipmentIdByStationId(Set<String> stationIdSet) {
        if (CollUtil.isEmpty(stationIdSet)) {
            return Collections.emptySet();
        }
        return sysStationMapper.findEquipmentIdByStationId(stationIdSet);
    }

}
